import { HashRouter, useHistory } from "react-router-dom";
//全局通用的路由实例
export const router = new HashRouter();
//将对象转化为查询字符串
export const formatObjectToQs = (obj) => {
    return Object.keys(obj).reduce(
        (prev, key) => `${prev}${key}=${obj[key]}&`,
        "?"
    );
};

// 将字符串转化为对象
export const formatQsTObject = (str) => {
    console.log("字符串", str);
    if (str.startsWith("?")) str.substring(1);
    return str.split("&").reduce((prev, curr) => {
        if (!curr) return prev;
        const [key, value] = curr.split("=");
        prev[key] = value;
        return prev;
    }, {});
};
//回到首页
export const handleBackToMain = () => {
    router.history.push("/");
};
//回到首页 hooks
export const useBackMain = () => {
    const history = useHistory();
    return () => history.push("/");
};
// 码表值转换
// export const getLabelByValue = (value, options) => {
//     const selectedOption = options.find((option) => option.value === value);
//     return selectedOption ? selectedOption.label : "";
// };

// export const getValueByLabel = (label, options) => {
//     const selectedOption = options.find((option) => option.label === label);
//     return selectedOption ? selectedOption.value : "";
// };
// 性能更好的 二分查找 缺点码表必须按次序排序好
export function getLabelByValue(value, options) {
    let left = 0;
    let right = options.length - 1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        const option = options[mid];
        if (option.value === value) {
            return option.label;
        } else if (value < option.value) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return "";
}

export function getValueByLabel(label, options) {
    let left = 0;
    let right = options.length - 1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        const option = options[mid];
        if (option.label === label) {
            return option.value;
        } else if (label < option.label) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return "";
}